<template>
    <div class="page-wrapper">
        <el-card class="!border-none mb-4" shadow="never">
            <el-form
                class="mb-[-16px]"
                :model="queryParams"
                inline
                label-width="100px"
            >
                <el-form-item label="日期">
                    <template #default>
                        <div class="w-[280px]">
                            <el-date-picker v-model="searchCreate_time" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="x" style="width: 100%;" @change="searchCreateTimeFun">
                            </el-date-picker>
                        </div>
                    </template>
                </el-form-item>
                <el-form-item label="店名" prop="shop_title">
                    <el-input class="w-[280px]" v-model="queryParams.shop_title" clearable placeholder="请输入店名" />
                </el-form-item>
                <el-form-item label="主材" prop="material">
                    <el-input class="w-[280px]" v-model="queryParams.material" clearable placeholder="请输入主材" />
                </el-form-item>

                <el-form-item label="客户姓名" prop="customer_name">
                    <el-input class="w-[280px]" v-model="queryParams.customer_name" clearable placeholder="请输入客户姓名" />
                </el-form-item>
                <el-form-item label="电话" prop="customer_mobile">
                    <el-input class="w-[280px]" v-model="queryParams.customer_mobile" clearable placeholder="请输入电话" />
                </el-form-item>
                <el-form-item label="下单日期">
                    <template #default>
                        <div class="w-[280px]">
                            <el-date-picker v-model="searchOrder_time" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="x" style="width: 100%;" @change="searchOrderTimeFun">
                            </el-date-picker>
                        </div>
                    </template>
                </el-form-item>
                <!-- 可展开/收起的表单项 -->
                <!-- 使用 <transition> 组件包裹需要动画的 div -->
                <transition name="expand">
                    <!-- 使用 v-show 来控制显示/隐藏，保留DOM结构 -->
                    <div v-show="isExpanded" class="expandable-content">
                        <el-form-item label="任务" prop="task">
                            <el-input class="w-[280px]" v-model="queryParams.task" clearable placeholder="请输入任务" />
                        </el-form-item>
                        <el-form-item label="工长" prop="foreman">
                            <el-input class="w-[280px]" v-model="queryParams.foreman" clearable placeholder="请输入工长" />
                        </el-form-item>

                        <el-form-item label="地址" prop="customer_address">
                            <el-input class="w-[280px]" v-model="queryParams.customer_address" clearable placeholder="请输入地址" />
                        </el-form-item>
                        <el-form-item label="材质" prop="quality">
                            <el-input class="w-[280px]" v-model="queryParams.quality" clearable placeholder="请输入材质" />
                        </el-form-item>
                        <el-form-item label="是否全屋换管" prop="is_all_pipe">
                            <el-input class="w-[280px]" v-model="queryParams.is_all_pipe" clearable placeholder="请输入是否全屋换管" />
                        </el-form-item>
                        <el-form-item label="供暖方式" prop="heating_method">
                            <el-input class="w-[280px]" v-model="queryParams.heating_method" clearable placeholder="请输入供暖方式" />
                        </el-form-item>
                        <el-form-item label="管材类型" prop="pipe_type">
                            <el-input class="w-[280px]" v-model="queryParams.pipe_type" clearable placeholder="请输入管材类型" />
                        </el-form-item>
                        <el-form-item label="管家姓名" prop="manage_name">
                            <el-input class="w-[280px]" v-model="queryParams.manage_name" clearable placeholder="请输入管家姓名" />
                        </el-form-item>
                        <el-form-item label="管家电话" prop="manage_mobile">
                            <el-input class="w-[280px]" v-model="queryParams.manage_mobile" clearable placeholder="请输入管家电话" />
                        </el-form-item>
                        
                    <!-- 可以添加更多需要隐藏的表单项 -->
                    </div>
                </transition>

                
                <el-form-item style="width: 100%;">
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                    <!-- 展开/收起按钮 -->
                    <el-button type="primary" @click="toggleExpand">
                        {{ expandButtonText }}
                        <el-icon class="el-icon--right">
                            <!-- 动态组件显示图标 -->
                            <component :is="expandButtonIcon" />
                        </el-icon>
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none mt-4 table-card" shadow="never" ref="cardBottomRef">
            <div class="flex" style="margin-bottom: 10px;">
                <router-link :to="{path: getRoutePath('order.orderAdd')}">
                    <el-button type="primary" >新增</el-button>
                </router-link>
                <export-data
                    class="ml-2.5"
                    :fetch-fun="orderLists"
                    :page-size="pager.size"
                    :params="queryParams"
                    :isAddress="true"
                />
            </div>
            <el-table size="large" v-loading="pager.loading" :data="pager.lists" :max-height="tableMaxHeight">
                <el-table-column label="订单编号" prop="sn" min-width="200" align="center"/>
                <el-table-column label="店名" prop="shop_title" min-width="120" align="center"/>
                <el-table-column label="店员" prop="shop_name" min-width="100" align="center"/>
                <el-table-column label="主材" prop="material" min-width="100" align="center"/>
                <el-table-column label="任务" prop="task" min-width="100" align="center"/>
                <el-table-column label="工长" prop="foreman" min-width="100" align="center"/>
                <el-table-column label="材质" prop="quality" min-width="100" align="center"/>
                <el-table-column label="平米或组数" prop="group_square" min-width="120" align="center"/>
                <el-table-column label="是否全屋换管" prop="is_all_pipe" min-width="150" align="center"/>
                <el-table-column label="供暖方式" prop="heating_method" min-width="100" align="center"/>
                <el-table-column label="管材类型" prop="pipe_type" min-width="100" align="center"/>
                <el-table-column label="原暖气" prop="old_heating" min-width="100" align="center"/>
                <el-table-column label="新暖气" prop="new_heating" min-width="100" align="center"/>
                <el-table-column label="管家姓名" prop="manage_name" min-width="100" align="center"/>
                <el-table-column label="管家电话" prop="manage_mobile" min-width="100" align="center"/>
                <el-table-column label="客户姓名" prop="customer_name" min-width="120" align="center"/>
                <el-table-column label="客户电话" prop="customer_mobile" min-width="120" align="center"/>
                <el-table-column label="客户地址" prop="customer_address" min-width="120" align="center"/>
                <el-table-column label="合同编号" prop="contract_no" min-width="120" align="center"/>
                <el-table-column label="销售金额汇总" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.sale_price_total ? row.sale_price_total.toFixed(2) : 0 }}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="成本金额汇总"  min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.cost_price_total ? row.cost_price_total.toFixed(2) : 0 }}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="是否测量" prop="is_measure" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.is_measure == 1 ? '是' : '否' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="测量日期" prop="measure_time" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.measure_time ? timeFormat(row.measure_time * 1000) : '' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="测量师傅" prop="measure_name" min-width="120" align="center"/>
                <el-table-column label="测量图片" prop="measure_photos" min-width="120" align="center">
                    <template #default="{ row }">
                        <div class="image-preview-container">
                            <el-image :src="getPhoto(row.measure_photos)" :preview-src-list="row.measure_photos != '' ? row.measure_photos.split(',') : []" :z-index="999999" :preview-teleported="true"/>
                            <div class="preview-overlay">
                                <el-icon :size="30"><ZoomIn /></el-icon> <!-- 使用 Element Plus 的放大镜图标 -->
                            </div>
                        </div>
                        
                    </template>
                </el-table-column>
                <el-table-column label="是否支付" prop="is_pay" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.is_pay == 1 ? '是' : '否' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="支付时间" prop="pay_time" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.pay_time ? timeFormat(row.pay_time * 1000) : '' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="支付金额" prop="pay_money" min-width="120" align="center"/>
                <el-table-column label="支付图片" prop="pay_photos" min-width="120" align="center">
                    <template #default="{ row }">
                        <el-image :src="row.pay_photos" />
                    </template>
                </el-table-column>
                <el-table-column label="是否改管" prop="is_change" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.is_change == 1 ? '是' : '否' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="改管时间" prop="change_time" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.change_time ? timeFormat(row.change_time * 1000) : '' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="改管师傅" prop="change_name" min-width="120" align="center"/>
                <el-table-column label="改管图片" prop="change_photos" min-width="120" >
                    <template #default="{ row }">
                        <el-image :src="row.change_photos" lazy/>
                    </template>
                </el-table-column>
                
                <el-table-column label="是否发货" prop="is_send" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.is_send == 1 ? '是' : '否' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="发货时间" prop="send_time" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.send_time ? timeFormat(row.send_time * 1000) : '' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="是否收货" prop="is_receive" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.is_receive == 1 ? '是' : '否' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="收货时间" prop="receive_time" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.receive_time ? timeFormat(row.receive_time * 1000) : '' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="是否安装" prop="is_install" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.is_install == 1 ? '是' : '否' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="安装时间" prop="install_time" min-width="120" align="center">
                    <template #default="{ row }">
                        <span>{{ row.install_time ? timeFormat(row.install_time * 1000) : '' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="安装师傅" prop="install_name" min-width="120" align="center"/>
                <el-table-column label="安装图片" prop="install_photos" min-width="120" align="center">
                    <template #default="{ row }">
                        <el-image :src="row.install_photos" lazy />
                    </template>
                </el-table-column>
                <el-table-column label="资料图片" prop="info_photos" min-width="120" align="center">
                    <template #default="{ row }">
                        <div class="image-preview-container">
                            <el-image :src="getPhoto(row.info_photos)" :preview-src-list="row.info_photos != '' ? row.info_photos.split(',') : []" :z-index="999999" :preview-teleported="true"/>
                            <div class="preview-overlay">
                                <el-icon :size="30"><ZoomIn /></el-icon> <!-- 使用 Element Plus 的放大镜图标 -->
                            </div>
                        </div>
                        
                    </template>
                </el-table-column>
                <el-table-column label="备注" prop="remark" min-width="120" align="center"/>
                <el-table-column label="创建时间" prop="create_time" min-width="120" align="center"/>
                <el-table-column label="订单状态" prop="order_status" min-width="120" align="center">
                    <template #default="{ row }">
                        <span v-if="row.order_status == 0">已创建</span>
                        <span v-if="row.order_status == 1">已测量</span>
                        <span v-if="row.order_status == 2">已交底</span>
                        <span v-if="row.order_status == 3">已收款</span>
                        <span v-if="row.order_status == 4">已改管</span>
                        <span v-if="row.order_status == 5">已下单</span>
                        <span v-if="row.order_status == 6">已到货</span>
                        <span v-if="row.order_status == 7">已安装</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="160" fixed="right" align="center">
                    <template #default="{ row }">
                        <el-button link type="primary">
                            <router-link :to="{
                                path: getRoutePath('orderEdit'),
                                query: {
                                    id: row.id
                                }
                            }">
                                编辑
                            </router-link>

                        </el-button>
                        <el-button type="primary" link>
                            <router-link :to="{
                                path: getRoutePath('orderDetail'),
                                query: {
                                    id: row.id
                                }
                            }">
                                查看
                            </router-link>
                        </el-button>
                        <el-button link type="danger"
                            @click="handleDelete(row.id)">
                            删除
                        </el-button>
                        <!-- <WordUploadDialog /> -->
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" ref="paginationRef" />
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { onActivated } from 'vue'; 
import { orderLists, orderDelete, orderRecover } from '@/api/order'
import { usePaging } from '@/hooks/usePaging'
import { getRoutePath } from '@/router'
import feedback from '@/utils/feedback'
import { timeFormat } from '@/utils/util'
import type { ElCard } from 'element-plus'
import Pagination from '@/components/pagination/index.vue'

// 导入需要的图标
import { ArrowDown, ArrowUp, Search, RefreshRight } from '@element-plus/icons-vue';
// import { defineProps, defineEmits, computed } from 'vue';

// const props = defineProps({
//   foo: String
// });

// const emit = defineEmits(['change', 'delete']);
// 创建 refs 来获取 DOM 元素引用
const cardTopRef = shallowRef<InstanceType<typeof ElCard> | null>(null)
const cardBottomRef = shallowRef<InstanceType<typeof ElCard> | null>(null);
const paginationRef = shallowRef<InstanceType<typeof Pagination> | null>(null);

// 用于存储计算出的表格最大高度
const tableMaxHeight = ref(500);
const searchCreate_time = ref<Date>() // 搜索创建时间
const searchOrder_time = ref<Date>() // 搜索下单时间
const queryParams = reactive<any>({
    shop_title: '',
    material: '',
    customer_name: '',
    customer_mobile: '',
    task: '',
    foreman: '',
    customer_address: '',
    quality: '',
    is_all_pipe: '',
    heating_method: '',
    pipe_type: '',
    manage_name: '',
    manage_mobile: '',
    order_time: '',
    create_time: ''
})
// 分页
const { pager, getLists, resetPage, resetParams } = usePaging({
	fetchFun: orderLists,
	params: queryParams,
})

// 计算表格最大高度的函数
const calculateTableHeight = () => {
    console.log('calculateTableHeight',cardTopRef, toRaw(cardTopRef.value))
    // 使用 nextTick 确保 DOM 已经更新和渲染完成
    nextTick(() => {
        if (!cardTopRef.value || !cardBottomRef.value || !paginationRef.value) {
             console.warn('Refs not available for height calculation');
             return; // 确保所有引用的元素都已挂载
        }

        // 获取窗口可视高度
        const windowHeight = window.innerHeight;

        // 获取顶部卡片和底部卡片的位置信息
        const cardTopRect = cardTopRef.value.$el.getBoundingClientRect();
        const cardBottomRect = cardBottomRef.value.$el.getBoundingClientRect();

        // 获取分页器的高度
        const paginationHeight = paginationRef.value.$el.offsetHeight;

        // 估算需要减去的其他元素的高度
        // 1. 顶部卡片距离视口顶部的距离 (包括可能的页面顶部导航、margin等)
        const spaceAboveBottomCard = cardBottomRect.top;

        // 2. 底部卡片内容区中，分页器下方到卡片底部的空间 (包括分页器的 margin-bottom 和卡片底部的 padding)
        // el-card 默认 padding 是 20px
        // pagination div 有 mt-4，假设是 16px
        const spaceBelowPagination = paginationHeight + 16 + 20; // 分页器高度 + margin-top + 卡片底部padding

        // 3. 计算表格的最大高度
        // 总高度 - 顶部卡片及其上方空间 - 分页器及其下方空间 - 底部卡片顶部的 padding
        // 一个更简单的思路：
        // 视口总高度 - 底部卡片距离视口顶部的距离（即底部卡片及上方所有元素的高度）- 分页器高度 - 底部卡片底部 padding - 一些微调 buffer
        const buffer = 16; // 额外的微调空间，可能由边框、滚动条占位、误差等引起
        console.log('spaceAboveBottomCard',windowHeight, spaceAboveBottomCard, paginationHeight, 20, buffer)
        const calculatedHeight = windowHeight - spaceAboveBottomCard - paginationHeight - 80; // 20 是底部卡片的 padding-bottom

        // 确保计算出的高度不小于一个最小值 (例如 100px)
        // tableMaxHeight.value = Math.max(100, calculatedHeight);

        console.log('Calculated Table Max Height:', tableMaxHeight.value);
    });
};

// 处理窗口大小改变时重新计算表格高度
const handleResize = () => {
    calculateTableHeight();
};

// 删除订单
const handleDelete = async (id: any[] | number) => {
	await feedback.confirm('确定要删除？')
	await orderDelete({ id })
	getLists().then(() => {
		calculateTableHeight()
	})
}

const getPhoto = (list: string) => {
    let arr = list.split(',')
    return arr[0]
}

const getPhotos = (list: string) => {
    if(!list) return
    const urls = [];
    let arr = list.split(',')
    if (list) {
        const maintainUrls = list.split(',').filter(url => url.trim() !== ''); // 分割并过滤空字符串
        urls.push(...maintainUrls); // 将分割后的 URL 添加到列表中
    }
    const uniqueUrls = Array.from(new Set(arr));
    console.log(uniqueUrls)
    return uniqueUrls
}



onMounted(() => {
	getLists().then(() => {
		calculateTableHeight()
	})

    // 添加窗口resize事件监听器，用于响应窗口大小变化
    window.addEventListener('resize', handleResize);
})
// onActivated 钩子，在 keep-alive 组件激活时执行
onActivated(() => {
    // 组件激活时重新计算表格高度，以防窗口大小在失活期间改变
    calculateTableHeight();
    // 也可以选择在这里刷新列表数据
    // getLists();
})
// onUnmounted 钩子，在组件卸载前执行
onUnmounted(() => {
    // 组件卸载时移除窗口resize事件监听器，防止内存泄漏
    window.removeEventListener('resize', handleResize);
})


// 下单日期选择
const searchOrderTimeFun = (value: any) => {
    console.log(value)
    queryParams.order_time = value / 1000
}
// 创建日期选择
const searchCreateTimeFun = (value: any) => {
    console.log(value, queryParams)
    queryParams.create_time = value / 1000

    console.log(toRaw(queryParams))
}



// 控制展开/收起的状态
const isExpanded = ref(false); // 默认收起

// 切换展开/收起状态的函数
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
};

// 计算属性：根据状态显示不同的按钮文本
const expandButtonText = computed(() => isExpanded.value ? '收起筛选项' : '展开筛选项');

// 计算属性：根据状态显示不同的按钮图标
const expandButtonIcon = computed(() => isExpanded.value ? ArrowUp : ArrowDown);
</script>

<style scoped>
/* 最外层容器，确保宽度为100%，并且不产生自身的垂直滚动条 */
.page-wrapper {
  width: 100%; /* 宽度占满父容器 */
  box-sizing: border-box; /* 内边距和边框不挤占宽度 */
  /* 通常不需要给 body 或 page-wrapper 设置 overflow-y: hidden;
     因为我们的目标是让 el-table 内部滚动，而不是禁用页面滚动。
     如果页面内容确实多于视口高度，浏览器会自动出现页面滚动条，
     这是正常行为。
     我们在这里做的只是让 el-table 尽可能利用剩余空间并在内部滚动，
     从而避免 el-table 自身撑高页面导致页面滚动条出现。
  */
}
/* .el-card { ElCard 默认是块级元素，宽度 100%  } */

/* .mt-4 { margin-top: 16px; } */

/* 确保表格所在的卡片内边距不会影响高度计算太多，
   或者在计算时精确考虑内边距。
   ElCard 默认 padding 是 20px。
*/
.table-card {
    /* 可选：如果需要更精确控制，可以移除默认 padding，自行在内部元素上添加 */
    /* padding: 0 !important; */
}


    /* 容器样式 */
.image-preview-container {
  position: relative; /* 为内部绝对定位的元素提供参考 */
  display: inline-block; /* 让容器的大小包裹图片 */
  width: 100px; /* 设置容器大小，与 el-image 的 style 保持一致 */
  height: 100px;
  overflow: hidden; /* 隐藏溢出部分 */
  cursor: pointer; /* 鼠标悬停时显示手型，表示可点击 */
}

/* el-image 基础样式 */
.image-preview-container .el-image {
    width: 100%;
    height: 100%;
    display: block; /* 防止图片下方有空白 */
}

/* 占位符样式 */
.image-preview-container .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 20px; /* 调整图标大小 */
}

/* 预览叠加层样式 */
.image-preview-container .preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
  color: #fff; /* 放大镜图标颜色 */
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0; /* 默认隐藏 */
  transition: opacity 0.3s ease; /* 添加过渡动画 */
  pointer-events: none; /* 关键：使鼠标事件穿透这个叠加层，点击直接作用于下方的 el-image */
  z-index: 1; /* 确保在图片上方，但低于可能的其他浮层（如预览弹窗本身） */
}

/* 容器悬停时显示叠加层 */
.image-preview-container:hover .preview-overlay {
  opacity: 1;
}

/* 可以为图标单独设置大小 */
.image-preview-container .preview-overlay .el-icon {
   font-size: 30px; /* 放大镜图标大小 */
}


/* --- CSS 过渡样式 --- */

/* 定义过渡期间的属性和时长 */
.expand-enter-active,
.expand-leave-active {
  transition: max-height 0.5s ease-in-out; /* 动画时长和缓动函数 */
  overflow: hidden; /* 隐藏超出max-height的内容 */
}

/* 进入前的状态 (展开前) 和 离开后的状态 (收起后) */
.expand-enter-from,
.expand-leave-to {
  max-height: 0;
}

/* 进入后的状态 (展开后) 和 离开前的状态 (收起前) */
.expand-enter-to,
.expand-leave-from {
  /* 设置一个足够大的值，确保在展开时能完全显示内容 */
  /* 这个值需要大于或等于你的可折叠内容的实际最大高度 */
  max-height: 500px; /* 示例值，根据实际内容调整 */
}

/* --- End CSS 过渡样式 --- */

/* 调整可展开内容区域的底部间距，避免在展开后与按钮组太近 */
.expandable-content .el-form-item {
    margin-bottom: 15px !important; /* 确保此处有底部间距 */
}
</style>